package com.unswift.utils;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.exception.CoreException;

@Api(value="线程池公共操作类", author="unswift", date="2022-12-16", version="1.0.0")
public final class ThreadUtils {

	@ApiField("线程池对象，默认10个线程")
	private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
	
	@ApiMethod(value="执行一个异步线程", params=@ApiField("线程对象"))
	public static void execute(Runnable runnable){
		threadPool.execute(runnable);
	}
	
	@ApiMethod(value="执行一个 同步线程", params=@ApiField("同步线程对象"), returns=@ApiField("线程任务返回的对象"))
	public static <T> T executeWait(Callable<T> call){
		Future<T> result = threadPool.submit(call);
		try {
			return result.get();
		} catch(CoreException e){
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionUtils.exception("execute.thread.exception", e, e.getMessage());
		}
	}
	
	@ApiMethod(value="执行多个线程，所有线程都执行完成才返回", params=@ApiField("线程对象列表"), returns=@ApiField("线程任务返回的对象"))
	public static <T> List<Future<T>> executeWait(List<Callable<T>> tasks){
		try {
			return threadPool.invokeAll(tasks);
		} catch(CoreException e){
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionUtils.exception("execute.thread.exception", e, e.getMessage());
		}
	}
	
	@ApiMethod(value="获取线程池对象", returns=@ApiField("线程池对象"))
	public static ExecutorService getThreadPool() {
		return threadPool;
	}
	@ApiMethod(value="获取当前线程的描述性信息", returns=@ApiField("描述性信息"))
	public static String getThreadDescribe(){
		return "[Thread "+Thread.currentThread().getId()+"] ";
	}
	
}
